package com.jiangnan.ui.fragment

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide.init
import com.jiangnan.R
import com.jiangnan.api.service.CreditApiService
import com.jiangnan.databinding.FragmentMyBinding
import com.jiangnan.ui.activity.AllBorrowedActivity
import com.jiangnan.ui.activity.AllReturnedActivity
import com.jiangnan.ui.activity.BookCollectedActivity
import com.jiangnan.ui.activity.CertificateActivity
import com.jiangnan.ui.activity.CommentsActivity
import com.jiangnan.ui.activity.CreditActivity
import com.jiangnan.ui.activity.LoginActivity
import com.jiangnan.ui.activity.MyActivity
import com.jiangnan.ui.activity.OverduePayActivity
import com.jiangnan.ui.activity.RechargeActivity
import com.jiangnan.ui.activity.TransactionHistoryActivity
import com.jiangnan.util.CurrentHolder
import com.jiangnan.util.CurrentLoginInfo
import com.jiangnan.util.GlideUtil
import com.jiangnan.util.NavigationUtil
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.UserViewModel

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"


/**
 * A simple [Fragment] subclass.
 * Use the [MyFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class MyFragment : Fragment(), View.OnClickListener {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    private lateinit var binding: FragmentMyBinding
    private lateinit var userViewModel: UserViewModel
    private var currentUserId = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate<FragmentMyBinding>(inflater, R.layout.fragment_my, container, false)

        // 初始化布局内容
        initUI()
        initObservers()
        setClick()

        return binding.root
    }

    private fun initObservers() {
        userViewModel.user.observe(viewLifecycleOwner){
            if (it != null) {
                GlideUtil.loadImageWithPlaceholder(
                    requireContext(),
                    it.avatar!!,
                    R.drawable.img_default,
                    R.drawable.img_error,
                    binding.ivAvatar
                )
                binding.tvNickname.text = it.nickname
                binding.tvLocal.text = it.locale
                binding.tvCredit.text = "信誉度为 "+it.credit+"分"
                binding.tvMoney.text = "当前余额为 "+it.accountMoney+"元"
            }
        }

    }

    private fun setClick() {
        binding.btnQuit.setOnClickListener(this)
        binding.ivAvatar.setOnClickListener(this)
        binding.tvNickname.setOnClickListener(this)
        binding.ivCollecting1.setOnClickListener(this)
        binding.ivAuthority.setOnClickListener(this)
        binding.ivBorrowing.setOnClickListener(this)
        binding.imageView5.setOnClickListener(this)
        binding.ivRefresh.setOnClickListener(this)
        binding.ivCredit.setOnClickListener(this)
        binding.ivAccountPay.setOnClickListener(this)
        binding.ivOverduePay.setOnClickListener(this)
        binding.ivRecord.setOnClickListener(this)
        binding.ivCommunity.setOnClickListener(this)
    }

    private fun initUI() {
        /**
         * 加载头像
         */
//        SharedPrefUtil.getLoginInfo(requireContext()).let {
//            GlideUtil.loadImageWithPlaceholder(
//                requireContext(),
//                it!!.avatar,
//                R.drawable.img_default,
//                R.drawable.img_error,
//                binding.ivAvatar
//            )
//            binding.tvNickname.text = it.nickname
//            binding.tvLocal.text = it.locale
//        }
        currentUserId = SharedPrefUtil.getLoginInfo(requireContext())!!.id.toLong()
        userViewModel = ViewModelProvider(this).get(UserViewModel::class.java)

        userViewModel.loadUser(currentUserId)


    }


    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.btn_quit -> {
                // 清除登录状态
//                val sharedPref = requireContext().getSharedPreferences("app_preferences", Context.MODE_PRIVATE)
//                sharedPref.edit().putBoolean("is_logged_in", false).apply()

                // 跳转回登录页面
                NavigationUtil.navigateTo(requireContext(), LoginActivity::class.java, true)
                requireActivity().finish()
            }
            R.id.iv_avatar -> {
                NavigationUtil.navigateTo(requireContext(), MyActivity::class.java)
            }
            R.id.tv_nickname -> {
                NavigationUtil.navigateTo(requireContext(), MyActivity::class.java)
            }
            R.id.iv_collecting1 -> {
                NavigationUtil.navigateTo(requireContext(), BookCollectedActivity::class.java)
            }
            binding.ivAuthority.id -> {
                NavigationUtil.navigateTo(requireContext(), CertificateActivity::class.java)
            }
            R.id.iv_borrowing -> {
                NavigationUtil.navigateTo(requireContext(), AllBorrowedActivity::class.java)
            }
            R.id.imageView5 -> {
                NavigationUtil.navigateTo(requireContext(), AllReturnedActivity::class.java)
            }
            R.id.iv_refresh -> {
                userViewModel.loadUser(currentUserId)
            }
            R.id.iv_credit -> {
                NavigationUtil.navigateTo(requireContext(), CreditActivity::class.java)
            }
            R.id.iv_account_pay -> {
                NavigationUtil.navigateTo(requireContext(), RechargeActivity::class.java)
            }
            R.id.iv_overdue_pay -> {
                NavigationUtil.navigateTo(requireContext(), OverduePayActivity::class.java)
            }
            R.id.iv_record -> {
                NavigationUtil.navigateTo(requireContext(), TransactionHistoryActivity::class.java)
            }
            R.id.iv_community -> {
                NavigationUtil.navigateTo(requireContext(), CommentsActivity::class.java)
            }
        }
    }



    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment MyFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            MyFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}